package com.geyue.common.util;

import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 快递鸟API接口
 * Created by Lyon on 2017/4/14.
 */
public class LogisticsUtil {

    //电商ID
    private static final String EBusinessID = "1284657";
    //电商加密私钥，快递鸟提供，注意保管，不要泄漏
    private static final String AppKey = "39539e52-ac4e-442d-91dc-b190fcee3728";
    private static final String host = "http://api.kdniao.cc";
    private static final String path = "/Ebusiness/EbusinessOrderHandle.aspx";


    public static void main(String[] args) {
        String expNo = "701233243086";
        System.out.println(logistics(expNo));
//        System.out.println(orderNo(expNo));
    }

    /**
     * 查询物流信息
     * @param expNo
     * @return
     */
    public static String logistics(String expNo) {
        try {

            String expCode = orderNo(expNo);

            if(expCode == null || "".equals(expCode))
                return null;

            String requestData = "{'OrderCode':'','ShipperCode':'" + expCode + "','LogisticCode':'" + expNo + "'}";
            Map<String, String> params = new HashMap<String, String>();
            params.put("RequestData", URLEncoder.encode(requestData, "UTF-8"));
            params.put("EBusinessID", EBusinessID);
            params.put("RequestType", "1002");
            String dataSign = encrypt(requestData, AppKey, "UTF-8");
            params.put("DataSign", URLEncoder.encode(dataSign, "UTF-8"));
            params.put("DataType", "2");
            String method = "POST";
            Map<String, String> headers = new HashMap<String, String>();
            Map<String, String> querys = new HashMap<String, String>();

            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, params);
            String result = EntityUtils.toString(response.getEntity());

            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据单号查询快递公司
     * @param expNo
     * @return
     */
    public static String orderNo(String expNo) {

        try {
            String requestData = "{'LogisticCode':'" + expNo + "'}";
            Map<String, String> params = new HashMap<String, String>();
            params.put("RequestData", URLEncoder.encode(requestData, "UTF-8"));
            params.put("EBusinessID", EBusinessID);
            params.put("RequestType", "2002");
            String dataSign = encrypt(requestData, AppKey, "UTF-8");
            params.put("DataSign", URLEncoder.encode(dataSign, "UTF-8"));
            params.put("DataType", "2");
            String method = "POST";
            Map<String, String> headers = new HashMap<String, String>();
            Map<String, String> querys = new HashMap<String, String>();
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, params);
            String responseStr = EntityUtils.toString(response.getEntity());
            JSONObject jsonObj = new JSONObject(responseStr);
            //识别返回结果
            if(!jsonObj.getBoolean("Success"))
                return null;

            JSONArray array = jsonObj.getJSONArray("Shippers");

            JSONObject shipper = array.getJSONObject(0);

            if(shipper.isNull("ShipperCode"))
                return null;

            return shipper.getString("ShipperCode");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * Sign签名生成
     *
     * @param content  内容
     * @param keyValue Appkey
     * @param charset  编码方式
     * @return DataSign签名
     */
    @SuppressWarnings("unused")
    private static String encrypt(String content, String keyValue, String charset) throws UnsupportedEncodingException {
        if (keyValue != null) {
            return Base64.encode(MD5.md5(content + keyValue).getBytes(charset));
        }
        return Base64.encode(MD5.md5(content).getBytes(charset));
    }

}
